package com.yugao.fintech.draper.security.service.impl;

import com.yugao.fintech.draper.auth.dto.UserInfoVO;
import com.yugao.fintech.draper.core.constant.SecurityConstants;
import com.yugao.fintech.draper.security.service.SecurityUserDetailsService;
import com.yugao.fintech.draper.security.SecurityUser;
import com.yugao.fintech.draper.security.util.SecurityUserUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service("securityUserDetailServiceImpl")
@RequiredArgsConstructor
public class SecurityUserDetailServiceImpl implements SecurityUserDetailsService {

    private final SecurityUserManager securityUserManager;

    /**
     * 通过用户名从数据库中获取用户信息SystemUser和用户权限集合
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (SecurityUserUtil.getAuthType() == null) {
            // 系统用户，认证方式通过用户名 username 认证
            UserInfoVO userDTO = securityUserManager.findByName(username);
            UserDetails userDetails = getUserDetails(userDTO);
            return userDetails;
        } else {
            // 系统用户，认证方式通过用户名 手机号 认证
            return this.loadUserByMobile(username);
        }
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        return getUserDetails(securityUserManager.findByMobile(mobile));
    }

    private UserDetails getUserDetails(UserInfoVO systemUser) {
        if (Objects.nonNull(systemUser)) {
            String permissions = securityUserManager.findUserPermissions(systemUser.getUsername());
            boolean notLocked = StringUtils.equals(UserInfoVO.STATUS_VALID, systemUser.getStatus());
            SecurityUser authUser = new SecurityUser(systemUser.getUsername(), systemUser.getPassword(), true, true,
                    true, notLocked, AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
            BeanUtils.copyProperties(systemUser, authUser);
            return authUser;
        }
        return null;
    }

    /**
     * 是否支持此客户端校验
     *
     * @param clientId 目标客户端
     * @return true/false
     */
    @Override
    public boolean support(String clientId) {
        return SecurityConstants.ADMIN_CLIENT_ID.equals(clientId);
    }

}
